jquery - Api returns "No 'Access-Control-Allow-Origin' header is present on the requested resource." -


i have api server , works perfect. when website calls api-server , ask "action" below, throw error if returns 0 mails*

[allowcrosssitejson] [system.web.http.httppost] public newmessagelist getmessagesbyuser(string userid) {     list<messagelist> m = new list<messagelist>();     list<messages> s = db.messages.include(i => i.touser).include(i => i.fromuser).where(i => i.touser.id.tostring() == userid).tolist();     foreach (var item in s)     {         m.add(new messagelist() { date = item.datecreated, = item.fromuser.username, = item.touser.username, message = item.text, subject = item.subject, key = item.id.tostring(), fromfirstname = item.fromuser.firstname, fromlastname = item.fromuser.lastname });     }      return new newmessagelist() { count = getunreadmessages(s.first().touser), messagelist = m }; } 

allowcrosssitejson attribute:

public class allowcrosssitejsonattribute : actionfilterattribute {    public override void onactionexecuted(httpactionexecutedcontext actionexecutedcontext)     {         if (actionexecutedcontext.response != null)             actionexecutedcontext.response.headers.add("access-control-allow-origin", "*");          base.onactionexecuted(actionexecutedcontext);     } } 

if getmessagebyuser returns 0 in messagelist returns following error:

xmlhttprequest cannot load http://localhost:56905/api/get/getmessagesbyuser/?userid=b852e7d4-d663-41d9-8db5-0b253df7c194. no 'access-control-allow-origin' header present on requested resource. origin 'http://localhost:54623' therefore not allowed access. response had http status code 500.

but if returns 1 or more in messagelist works perfect , runs without throwing error.

do have idea how fix this? can provide more code if needed.

in line:

return new newmessagelist() { count = getunreadmessages(s.first().touser), messagelist = m }; 

you accessing s.first() unconditionally. of course throws exception if list empty.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -