我们如何将XML作为请求传递给.Net核心API,并从c#中的同一API获得XML响应?
我想在我们如何将XML作为请求传递给.Net核心API,并从c#中的同一API获得XML响应?,c#,xml,asp.net-core,asp.net-core-webapi,C#,Xml,Asp.net Core,Asp.net Core Webapi,我想在.netcore中创建一个API,它接受XML请求并仅以XML给出响应 我已经搜索并创建了示例,但当我使用XML请求点击API请求时,它不起作用 调试器未到达控制器 我还在startup.cs类的configure服务中添加了以下代码行 services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; // false by default
.netcore
中创建一个API,它接受XML
请求并仅以XML给出响应
我已经搜索并创建了示例,但当我使用XML
请求点击API
请求时,它不起作用
调试器未到达控制器
我还在startup.cs类的configure服务中添加了以下代码行
services.AddMvc(options =>
{
options.RespectBrowserAcceptHeader = true; // false by default
options.InputFormatters.Insert(0, new XDocumentInputFormatter());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddXmlSerializerFormatters()
.AddXmlDataContractSerializerFormatters();
POST
方法已写入控制器,如下所示
[Produces("application/xml")]
[ProducesResponseType(typeof(CustomerDetails), (int)HttpStatusCode.OK)]
[HttpPost("CustomerDetails", Name = "CustomerDetails")]
public IActionResult CustomerDetails([FromBody] CustomerDetails CustReq)
{
var resp = new CustomerDetails
{
BankId="1234567"
};
return Ok(resp);
}
处理邮递员的请求时出错。
处理请求时发生未处理的异常。
InvalidCastException:无法将“System.Xml.Linq.XDocument”类型的对象强制转换为“CustomerValidationAPI.Models.CustomerDetails”类型
下面是我想处理的XML
请求
它也有多个节点,我们如何处理
<?xml version="1.0" encoding="UTF-8"?>
<FIXML xmlns="http://www.finacle.com/fixml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.finacle.com/fixml
executeFinacleScript.xsd">
<Header>
<RequestHeader>
<MessageKey>
<RequestUUID>FEBA_1553756445880</RequestUUID>
<ServiceRequestId>executeFinacleScript</ServiceRequestId>
<ServiceRequestVersion>10.2</ServiceRequestVersion>
<ChannelId>COR</ChannelId>
</MessageKey>
<RequestMessageInfo>
<BankId>04</BankId>
<TimeZone>GMT+05:00</TimeZone>
<EntityId />
<EntityType />
<ArmCorrelationId />
<MessageDateTime>2019-03-28T11:00:45.880</MessageDateTime>
</RequestMessageInfo>
<Security>
<Token>
<PasswordToken>
<UserId>11111</UserId>
<Password />
</PasswordToken>
</Token>
<FICertToken />
<RealUserLoginSessionId />
<RealUser />
<RealUserPwd />
<SSOTransferToken />
</Security>
</RequestHeader>
</Header>
<Body>
<executeFinacleScriptRequest>
<ExecuteFinacleScriptInputVO>
<requestId>validateAcct.scr</requestId>
</ExecuteFinacleScriptInputVO>
<executeFinacleScript_CustomData>
<ACCT_NUM>01122507576</ACCT_NUM>
<PHONE_NUM>59887834</PHONE_NUM>
<NIC>G2105493001653</NIC>
</executeFinacleScript_CustomData>
</executeFinacleScriptRequest>
</Body>
</FIXML>
我的创业班
public void配置服务(IServiceCollection服务)
{
services.AddMvc(选项=>
{
options.reserverBrowserAcceptHeader=true;//默认为false
Insert(0,新XDocumentInputFormatter());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddXmlSerializerFormatters()
.AddXmlDataContractSerializerFormatters();
}
类中的XDocumentInputFormatter已采取以下措施。。
公共类XDocumentInputFormatter:InputFormatter、IIInputFormatter、IAPIRequestFormattMetadataProvider
{
公共XDocumentInputFormatter()
{
SupportedMediaTypes.Add(“应用程序/xml”);
}
受保护的覆盖布尔CanReadType(类型)
{
if(type.IsAssignableFrom(typeof(XDocument)))返回true;
返回base.CanReadType(类型);
}
//公共重写异步任务ReadRequestBodyAsync(InputFormatterContext上下文)
//{
//var xmlDoc=await XDocument.LoadAsync(context.HttpContext.Request.Body,LoadOptions.None,CancellationToken.None);
//返回InputFormatterResult.Success(xmlDoc);
//}
公共重写异步任务ReadRequestBodyAsync(InputFormatterContext上下文)
{
//使用StreamReader将任何编码转换为UTF-16(默认C#和sql Server)。
使用(var streamReader=newstreamreader(context.HttpContext.Request.Body))
{
var xmlDoc=wait XDocument.LoadAsync(streamReader、LoadOptions.None、CancellationToken.None);
返回InputFormatterResult.Success(xmlDoc);
}
}
}
我现在犯了一个错误
处理请求时发生未处理的异常。
无效操作例外:http://www.finacle.com/fixml“>这是意料之中的
Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderTestClass.Read3_TestClass()
InvalidOperationException:XML文档(1174)中存在错误
反序列化(XmlReader XmlReader,字符串编码样式,XmlDeserializationEvents)
从XML创建类,如下所示
公共类XMLClass
{
//注意:生成的代码可能至少需要.NET Framework 4.5或.NET Core/Standard 2.0。
///
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute(“代码”)]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true,命名空间=”http://www.finacle.com/fixml")]
[System.Xml.Serialization.XmlRootAttribute(命名空间=”http://www.finacle.com/fixml“,IsNullable=false)]
公共部分类FIXML
{
专用固定头字段;
私人固定体字段;
///
公共固定报头
{
得到
{
返回这个.headerField;
}
设置
{
this.headerField=值;
}
}
///
公共机构
{
得到
{
返回此.bodyField;
}
设置
{
this.bodyField=值;
}
}
}
///
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute(“代码”)]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true,命名空间=”http://www.finacle.com/fixml")]
公共部分类FIXMLHeader
{
private FIXMLHeaderRequestHeader requestHeaderField;
///
公共FIXMLHeaderRequestHeader请求标头
{
得到
{
返回此.requestHeaderField;
}
设置
{
this.requestHeaderField=值;
}
}
}
///
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute(“代码”)]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true,命名空间=”http://www.finacle.com/fixml")]
公共部分类FIXMLHeaderRequestHeader
{
私有fixmlHeaderRequestHeaderMessageKeyField;
private FIXMLHeaderRequestHeaderRequestMessageInfo请求消息信息字段;
私人FixmlHeaderRequestHeaderSecuritySecurityField;
///
public FIXMLHeaderRequestHeaderMessageKey消息密钥
{
得到
{
返回此.messageKeyField;
}
设置
{
public class CustomerDetails
{
[Required]
public string RequestUUID { get; set; }
[Required]
public string ServiceRequestId { get; set; }
[Required]
public string ServiceRequestVersion { get; set; }
[Required]
public string ChannelId { get; set; }
[Required]
public string BankId { get; set; }
[Required]
public string TimeZone { get; set; }
public string EntityId { get; set; }
public string EntityType { get; set; }
public string ArmCorrelationId { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime MessageDateTime { get; set; }
[Required]
public string Password { get; set; }
public string FICertToken { get; set; }
public string RealUserLoginSessionId { get; set; }
public string RealUser { get; set; }
public string RealUserPwd { get; set; }
public string SSOTransferToken { get; set; }
[Required]
public string requestId { get; set; }
[Required]
public string ACCT_NUM { get; set; }
[Required]
public string PHONE_NUM { get; set; }
[Required]
public string NIC { get; set; }
}
My startUp class
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.RespectBrowserAcceptHeader = true; // false by default
options.InputFormatters.Insert(0, new XDocumentInputFormatter());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddXmlSerializerFormatters()
.AddXmlDataContractSerializerFormatters();
}
XDocumentInputFormatter in class have taken as below..
public class XDocumentInputFormatter : InputFormatter, IInputFormatter, IApiRequestFormatMetadataProvider
{
public XDocumentInputFormatter()
{
SupportedMediaTypes.Add("application/xml");
}
protected override bool CanReadType(Type type)
{
if (type.IsAssignableFrom(typeof(XDocument))) return true;
return base.CanReadType(type);
}
//public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
//{
// var xmlDoc = await XDocument.LoadAsync(context.HttpContext.Request.Body, LoadOptions.None, CancellationToken.None);
// return InputFormatterResult.Success(xmlDoc);
//}
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
// Use StreamReader to convert any encoding to UTF-16 (default C# and sql Server).
using (var streamReader = new StreamReader(context.HttpContext.Request.Body))
{
var xmlDoc = await XDocument.LoadAsync(streamReader, LoadOptions.None, CancellationToken.None);
return InputFormatterResult.Success(xmlDoc);
}
}
}
Created the Class from XML as below
public class XMLClass
{
// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.finacle.com/fixml", IsNullable = false)]
public partial class FIXML
{
private FIXMLHeader headerField;
private FIXMLBody bodyField;
/// <remarks/>
public FIXMLHeader Header
{
get
{
return this.headerField;
}
set
{
this.headerField = value;
}
}
/// <remarks/>
public FIXMLBody Body
{
get
{
return this.bodyField;
}
set
{
this.bodyField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLHeader
{
private FIXMLHeaderRequestHeader requestHeaderField;
/// <remarks/>
public FIXMLHeaderRequestHeader RequestHeader
{
get
{
return this.requestHeaderField;
}
set
{
this.requestHeaderField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLHeaderRequestHeader
{
private FIXMLHeaderRequestHeaderMessageKey messageKeyField;
private FIXMLHeaderRequestHeaderRequestMessageInfo requestMessageInfoField;
private FIXMLHeaderRequestHeaderSecurity securityField;
/// <remarks/>
public FIXMLHeaderRequestHeaderMessageKey MessageKey
{
get
{
return this.messageKeyField;
}
set
{
this.messageKeyField = value;
}
}
/// <remarks/>
public FIXMLHeaderRequestHeaderRequestMessageInfo RequestMessageInfo
{
get
{
return this.requestMessageInfoField;
}
set
{
this.requestMessageInfoField = value;
}
}
/// <remarks/>
public FIXMLHeaderRequestHeaderSecurity Security
{
get
{
return this.securityField;
}
set
{
this.securityField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLHeaderRequestHeaderMessageKey
{
private string requestUUIDField;
private string serviceRequestIdField;
private decimal serviceRequestVersionField;
private string channelIdField;
/// <remarks/>
public string RequestUUID
{
get
{
return this.requestUUIDField;
}
set
{
this.requestUUIDField = value;
}
}
/// <remarks/>
public string ServiceRequestId
{
get
{
return this.serviceRequestIdField;
}
set
{
this.serviceRequestIdField = value;
}
}
/// <remarks/>
public decimal ServiceRequestVersion
{
get
{
return this.serviceRequestVersionField;
}
set
{
this.serviceRequestVersionField = value;
}
}
/// <remarks/>
public string ChannelId
{
get
{
return this.channelIdField;
}
set
{
this.channelIdField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLHeaderRequestHeaderRequestMessageInfo
{
private byte bankIdField;
private string timeZoneField;
private object entityIdField;
private object entityTypeField;
private object armCorrelationIdField;
private System.DateTime messageDateTimeField;
/// <remarks/>
public byte BankId
{
get
{
return this.bankIdField;
}
set
{
this.bankIdField = value;
}
}
/// <remarks/>
public string TimeZone
{
get
{
return this.timeZoneField;
}
set
{
this.timeZoneField = value;
}
}
/// <remarks/>
public object EntityId
{
get
{
return this.entityIdField;
}
set
{
this.entityIdField = value;
}
}
/// <remarks/>
public object EntityType
{
get
{
return this.entityTypeField;
}
set
{
this.entityTypeField = value;
}
}
/// <remarks/>
public object ArmCorrelationId
{
get
{
return this.armCorrelationIdField;
}
set
{
this.armCorrelationIdField = value;
}
}
/// <remarks/>
public System.DateTime MessageDateTime
{
get
{
return this.messageDateTimeField;
}
set
{
this.messageDateTimeField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLHeaderRequestHeaderSecurity
{
private FIXMLHeaderRequestHeaderSecurityToken tokenField;
private object fICertTokenField;
private object realUserLoginSessionIdField;
private object realUserField;
private object realUserPwdField;
private object sSOTransferTokenField;
/// <remarks/>
public FIXMLHeaderRequestHeaderSecurityToken Token
{
get
{
return this.tokenField;
}
set
{
this.tokenField = value;
}
}
/// <remarks/>
public object FICertToken
{
get
{
return this.fICertTokenField;
}
set
{
this.fICertTokenField = value;
}
}
/// <remarks/>
public object RealUserLoginSessionId
{
get
{
return this.realUserLoginSessionIdField;
}
set
{
this.realUserLoginSessionIdField = value;
}
}
/// <remarks/>
public object RealUser
{
get
{
return this.realUserField;
}
set
{
this.realUserField = value;
}
}
/// <remarks/>
public object RealUserPwd
{
get
{
return this.realUserPwdField;
}
set
{
this.realUserPwdField = value;
}
}
/// <remarks/>
public object SSOTransferToken
{
get
{
return this.sSOTransferTokenField;
}
set
{
this.sSOTransferTokenField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLHeaderRequestHeaderSecurityToken
{
private FIXMLHeaderRequestHeaderSecurityTokenPasswordToken passwordTokenField;
/// <remarks/>
public FIXMLHeaderRequestHeaderSecurityTokenPasswordToken PasswordToken
{
get
{
return this.passwordTokenField;
}
set
{
this.passwordTokenField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLHeaderRequestHeaderSecurityTokenPasswordToken
{
private ushort userIdField;
private object passwordField;
/// <remarks/>
public ushort UserId
{
get
{
return this.userIdField;
}
set
{
this.userIdField = value;
}
}
/// <remarks/>
public object Password
{
get
{
return this.passwordField;
}
set
{
this.passwordField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLBody
{
private FIXMLBodyExecuteFinacleScriptRequest executeFinacleScriptRequestField;
/// <remarks/>
public FIXMLBodyExecuteFinacleScriptRequest executeFinacleScriptRequest
{
get
{
return this.executeFinacleScriptRequestField;
}
set
{
this.executeFinacleScriptRequestField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLBodyExecuteFinacleScriptRequest
{
private FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScriptInputVO executeFinacleScriptInputVOField;
private FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScript_CustomData executeFinacleScript_CustomDataField;
/// <remarks/>
public FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScriptInputVO ExecuteFinacleScriptInputVO
{
get
{
return this.executeFinacleScriptInputVOField;
}
set
{
this.executeFinacleScriptInputVOField = value;
}
}
/// <remarks/>
public FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScript_CustomData executeFinacleScript_CustomData
{
get
{
return this.executeFinacleScript_CustomDataField;
}
set
{
this.executeFinacleScript_CustomDataField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScriptInputVO
{
private string requestIdField;
/// <remarks/>
public string requestId
{
get
{
return this.requestIdField;
}
set
{
this.requestIdField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScript_CustomData
{
private uint aCCT_NUMField;
private uint pHONE_NUMField;
private string nICField;
/// <remarks/>
public uint ACCT_NUM
{
get
{
return this.aCCT_NUMField;
}
set
{
this.aCCT_NUMField = value;
}
}
/// <remarks/>
public uint PHONE_NUM
{
get
{
return this.pHONE_NUMField;
}
set
{
this.pHONE_NUMField = value;
}
}
/// <remarks/>
public string NIC
{
get
{
return this.nICField;
}
set
{
this.nICField = value;
}
}
}
}
public class Token
{
public PasswordToken PasswordToken{get;set;}
}
public class PasswordToken
{
public string UserId{get;set;}
public string Password{get;set;}
}
public class Body
{
public executeFinacleScriptRequest executeFinacleScriptRequest{get;set;}
}
public class executeFinacleScriptRequest
{
public ExecuteFinacleScriptInputVO ExecuteFinacleScriptInputVO{get;set;}
public executeFinacleScript_CustomData executeFinacleScript_CustomData{get;set;}
}
public class ExecuteFinacleScriptInputVO
{
public string requestId{get;set;}
}
public class executeFinacleScript_CustomData
{
public string ACCT_NUM{get;set;}
public string PHONE_NUM{get;set;}
public string NIC{get;set;}
}
services.AddMvc(options =>
{
options.RespectBrowserAcceptHeader = true; // false by default
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddXmlSerializerFormatters()
.AddXmlDataContractSerializerFormatters();
<PackageReference Include="Microsoft.AspNetCore.Mvc.Formatters.Xml" Version="1.1.3" />
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddXmlSerializerFormatters();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.FormatterMappings.SetMediaTypeMappingForFormat
("xml", MediaTypeHeaderValue.Parse("application/xml"));
options.FormatterMappings.SetMediaTypeMappingForFormat
("config", MediaTypeHeaderValue.Parse("application/xml"));
options.FormatterMappings.SetMediaTypeMappingForFormat
("js", MediaTypeHeaderValue.Parse("application/json"));
})
.AddXmlSerializerFormatters();