Home Ask Login Register

Developers Planet

Your answer is one click away!

Carsten Løvbo Andersen February 2016

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

I have an Api server and it works almost perfect. When my website calls the Api-server and ask for "action" below, it throw an error if it returns 0 mails*

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, From = item.FromUser.Username, To = 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", "*");


If GetMessageByUser returns 0 in MessageList It returns the following error:

XMLHttpRequest cannot load http://localhost:56905/api/Get/GetMessagesbyUser/?userid=b852e7d4-d663-41d9-8db5-0b253df7c194. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:54623' is therefore not allowed access. The response had HTTP status code 500.

But if it returns 1 or mor


ElmoVanKielmo February 2016

In this line:

return new newMessageList() { Count = GetUnreadMessages(s.First().ToUser), MessageList = m };

you are accessing s.First() unconditionally. Of course it throws exception if the list is empty.

Post Status

Asked in February 2016
Viewed 1,287 times
Voted 14
Answered 1 times


Leave an answer

Quote of the day: live life