从代码隐藏文件调用时获取对Web api的未授权访问

时间:2016-03-25 08:52:59

标签: asp.net ajax asp.net-mvc asp.net-web-api

我正在使用GuestController控制器类。我将从ajax以及代码隐藏文件中访问此GetGuestBookingIdByRoomId api方法。这个方法在ajax调用时返回正确的结果,但在代码中后面的错误“StatusCode:401,ReasonPhrase:'Unauthorized'”

Api控制器:

[Authorize]
public class GuestController : ApiController
{

    public int GetGuestBookingIdByRoomId(int roomId)
    {
        return GuestManager.GetGuestBookingIdByRoomId(roomId);
    } // GetGuestBookingIdByRoomId
}

Ajax电话:

function getGuestBookingIdByRoomId(roomId) {
    $.ajax({
        url: _pageURL + "/api/Guest/GetGuestBookingIdByRoomId",
        type: "GET",
        data: { roomId: roomId },
        dataType: "json",
        success: function (bookingId) {
            if (bookingId != undefined && bookingId != null && bookingId > 0) {  
                _receiverBookingId = bookingId;
            } else {
                // Do Nothing                             
            }
        },
    });
} 
来自代码的api调用:

private int GetReceiverBookingId(int roomId)
{
    int receiverBookingId = 0;
    // Create object of http client 
    HttpClient client = new HttpClient();
    // assign Base address
    client.BaseAddress = new Uri("http://" + Request.Url.Authority);
    // Set request header
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    // build web api url
    var url = "/api/Guest/GetGuestBookingIdByRoomId?roomId=" + roomId;
    // Call web api method
    HttpResponseMessage response = client.GetAsync(url).Result;
    if (response.IsSuccessStatusCode) // If web api call is successfull  
    {
        receiverBookingId = response.Content.ReadAsAsync<int>().Result;
    }
    else
    {

    }       
     return receiverBookingId;
} 

0 个答案:

没有答案