编程语言
首页 > 编程语言> > C#-WebAPI在IIS中不返回xml

C#-WebAPI在IIS中不返回xml

作者:互联网

我一直在努力解决这个问题,以便找到根源,但是还没有运气.我的WebAPI在IIS中自己的应用程序池中运行,并且该操作假定返回XMLJSON,但仅返回JSON.更为奇怪的是,它在其他PC上运行良好,因此我猜测是IIS一定有问题,或者我缺少某种配置.如果我使用Visual Studio Server但不使用IIS,则效果很好.

API配置:

//Added to support .net1.1 clients
config.Formatters.XmlFormatter.UseXmlSerializer = true;
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = true;
config.Formatters.Add(new FormUrlEncodedMediaTypeFormatter());

数据属性:

/// <summary>
/// Unique Transaction ID
/// </summary>
private int TransactionID;
[XmlElement(Type = typeof(int))]
public int fTransactionID
{
    get{return TransactionID;}
    set{TransactionID = value;}
}

请求标题

// Create a WebRequest to the remote site
WebRequest myWebClient = WebRequest.Create(uri);
myWebClient.ContentType = "application/xml";
myWebClient.Method = method;

编辑

API方法

/// <summary>
/// Return Rebate Reversal Transactions
/// </summary>
/// <param name="FromDate"></param>
/// <param name="ToDate"></param>
/// <param name="PracticeID"></param>
/// <returns></returns>
[AttributeRouting.Web.Http.GET("RebateReversalTransaction/{FromDate}/{ToDate}/{PracticeID}")]
public GetRebateReversalTransactionResponse GetReversalTransaction(int FromDate, int ToDate, int PracticeID)
{
    GetRebateReversalTransactionResponse reversalResponse = new GetRebateReversalTransactionResponse();
    service = new PPNRebateSystemService();
    reversalResponse = service.GetPracticeRebateReversalTransactions(FromDate, ToDate, PracticeID);

    return reversalResponse;
}

解决方法:

在Global.asax.cs中,将以下代码添加到Application_Start.这将清除所有可能已注册的格式化程序,然后重新添加XML格式化程序.我已经对此进行了测试,即使客户端发送JSON Accept标头(Accept:application / json),它也会以XML响应.

protected void Application_Start() 
{
    ...


    GlobalConfiguration.Configuration.Formatters.Clear();
    //Force XML responses on all requests
    GlobalConfiguration.Configuration.Formatters.Add(new XmlMediaTypeFormatter());
    //Force JSON responses on all requests
    //GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());

}

标签:asp-net-web-api,iis,c
来源: https://codeday.me/bug/20191121/2052169.html