- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
尝试将文件添加到 http rest 调用时出现此错误:
responseJson = {Message: "An error has occurred.", ExceptionMessage: "Invalid 'HttpContent' instance provided. It does n…rting with 'multipart/'. ↵Parameter name: content", ExceptionType: "System.ArgumentException", StackTrace: " at System.Net.Http.Formatting.Parsers.MimeMulti…tpControllerDispatcher.d__1.MoveNext()"}
我的 react 组件:
import React, { Component } from 'react';
import { Row, Col } from 'antd';
import PageHeader from '../../components/utility/pageHeader';
import Box from '../../components/utility/box';
import LayoutWrapper from '../../components/utility/layoutWrapper.js';
import ContentHolder from '../../components/utility/contentHolder';
import basicStyle from '../../settings/basicStyle';
import IntlMessages from '../../components/utility/intlMessages';
import { adalApiFetch } from '../../adalConfig';
export default class extends Component {
constructor(props) {
super(props);
this.state = {TenantId: '', TenantUrl: '', TenantPassword: '' };
this.handleChangeTenantUrl = this.handleChangeTenantUrl.bind(this);
this.handleChangeTenantPassword = this.handleChangeTenantPassword.bind(this);
this.handleChangeTenantId= this.handleChangeTenantId.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
};
handleChangeTenantUrl(event){
this.setState({TenantUrl: event.target.value});
}
handleChangeTenantPassword(event){
this.setState({TenantPassword: event.target.value});
}
handleChangeTenantId(event){
this.setState({TenantId: event.target.value});
}
handleSubmit(event){
event.preventDefault();
const formData = new FormData();
formData.append("TenantId", this.state.TenantId);
formData.append("TenantUrl", this.state.TenantUrl);
formData.append("TenantPassword", this.state.TenantPassword);
const options = {
method: 'put',
data: formData,
config: {
headers: {
'Content-Type': 'multipart/form-data'
}
}
};
adalApiFetch(fetch, "/Tenant", options)
.then(response => response.json())
.then(responseJson => {
if (!this.isCancelled) {
this.setState({ data: responseJson });
}
})
.catch(error => {
console.error(error);
});
}
upload(e){
let data = new FormData();
//Append files to form data
let files = e.target.files;
for (let i = 0; i < files.length; i++) {
data.append('files', files[i], files[i].name);
}
}
render(){
const { data } = this.state;
const { rowStyle, colStyle, gutter } = basicStyle;
return (
<div>
<LayoutWrapper>
<PageHeader>{<IntlMessages id="pageTitles.TenantAdministration" />}</PageHeader>
<Row style={rowStyle} gutter={gutter} justify="start">
<Col md={12} sm={12} xs={24} style={colStyle}>
<Box
title={<IntlMessages id="pageTitles.TenantAdministration" />}
subtitle={<IntlMessages id="pageTitles.TenantAdministration" />}
>
<ContentHolder>
<form onSubmit={this.handleSubmit}>
<label>
TenantId:
<input type="text" value={this.state.TenantId} onChange={this.handleChangeTenantId} />
</label>
<label>
TenantUrl:
<input type="text" value={this.state.TenantUrl} onChange={this.handleChangeTenantUrl} />
</label>
<label>
TenantPassword:
<input type="text" value={this.state.TenantPassword} onChange={this.handleChangeTenantPassword} />
</label>
<label>
Certificate:
<input onChange = { e => this.upload(e) } type = "file" id = "files" ref = { file => this.fileUpload } />
</label>
<input type="submit" value="Submit" />
</form>
</ContentHolder>
</Box>
</Col>
</Row>
</LayoutWrapper>
</div>
);
}
}
我的租户 Controller Put 方法
[HttpPut]
public async Task<IHttpActionResult> PutTenant([FromBody]Tenant tenant)
{
var provider = new MultipartMemoryStreamProvider();
var contentType = "";
var content = new byte[0];
await base.Request.Content.ReadAsMultipartAsync(provider);
if (provider.Contents.Count > 0)
{
contentType = provider.Contents[0].Headers.ContentType.MediaType;
content = await provider.Contents[0].ReadAsByteArrayAsync();
}
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureStorageKey"].ToString());
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(ConfigurationManager.AppSettings["certificatesContainer"].ToString());
// Retrieve reference to a blob named "myblob".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");
// Create or overwrite the "myblob" blob with contents from a local file.
blockBlob.Properties.ContentType = contentType;
MemoryStream stream = new MemoryStream(content);
blockBlob.UploadFromStream(stream);
var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
tenant.content = content;
tenant.CertificatePath = blockBlob.Uri;
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var added = await tenantStore.AddAsync(tenant);
return StatusCode(HttpStatusCode.NoContent);
}
和租户POCO
public class Tenant
{
public string TenantId { get; set; }
public string TenantUrl { get; set; }
public Uri CertificatePath { get; set; }
public string CertificatePassword { get; set; }
public byte[] content { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
堆栈跟踪:
" at System.Net.Http.Formatting.Parsers.MimeMultipartBodyPartParser.ValidateArguments(HttpContent content, Int64 maxMessageSize, Boolean throwOnError)
at System.Net.Http.Formatting.Parsers.MimeMultipartBodyPartParser..ctor(HttpContent content, MultipartStreamProvider streamProvider, Int64 maxMessageSize, Int32 maxBodyPartHeaderSize)
at System.Net.Http.HttpContentMultipartExtensions.<ReadAsMultipartAsync>d__0`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at TenantManagementWebApi.Controllers.TenantController.<PutTenant>d__2.MoveNext() in C:\Users\levm3\source\repos\TenantManagementWebApi\Controllers\TenantController.cs:line 48
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__3`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
更新 1:
当我远程附加调试器时,租户参数为空,因此在客户端组件上设置参数时肯定有问题。
最佳答案
我猜你的 [FromBody]Tenant tenant
是空的,因为你使用了 multipart/form-data
。
在这种情况下,默认模型绑定(bind)器无法解析您的模型。
请查看来自 Microsoft 的示例 documentation (第 Reading Form Control Data 节)。
您需要使用 MultipartFormDataStreamProvider
读取您的模型数据。如我所见,您仅将提供程序用于文件内容读取。但您也可以从 FormData
属性中读取您的模型数据(如 TenantId、TenantUrl 等)。
作为第二种(也是更通用的)方法,您可以创建自己的 IModelBinder实现。
在这里你可以查看我实现 IModelBinder 的例子(它是来自真实项目的代码):
public class NativeTranslateModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(NativeTranslateViewModel))
{
return false;
}
var task = Task.Run(async () =>
{
var model = new NativeTranslateViewModel();
if (!actionContext.Request.Content.IsMimeMultipartContent())
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "WebRequeest content 'multipart/form-data' is valid");
}
else
{
var provider = await actionContext.Request.Content.ReadAsMultipartAsync();
var fileContent = provider.Contents.FirstOrDefault(n => n.Headers.ContentDisposition.Name.Equals("file"));
if (fileContent == null)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Section 'file' is missed");
}
var modelContent = provider.Contents.FirstOrDefault(n => n.Headers.ContentDisposition.Name.Equals("model"));
if (modelContent == null)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Section 'model' is missed");
}
if (fileContent != null && modelContent != null)
{
model = JsonConvert.DeserializeObject<NativeTranslateViewModel>(await modelContent.ReadAsStringAsync());
model.Text = "<NativeTranslation>";
model.FileData = await fileContent.ReadAsByteArrayAsync();
model.FileName = fileContent.Headers.ContentDisposition.FileName;
}
}
return model;
});
task.Wait();
bindingContext.Model = task.Result;
return true;
}
}
我们可以很容易地使用新模型绑定(bind)器:
[HttpPost]
public HttpResponseMessage UploadNativeDocument([ModelBinder(typeof(NativeTranslateModelBinder))] NativeTranslateViewModel model)
现在我们可以在 Controller 操作中使用我们的模型和模型属性。
关于c# - 发生错误 .", ExceptionMessage: "提供的实例无效 'HttpContent',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51368982/
我们在代码库中看到了以下堆栈跟踪: System.ArgumentException: An item with the same key has already been added. at
我有这个代码示例,它是作为对另一个问题 (Send a file via HTTP POST with C#) 的回答而发布的。除了一个问题外,它工作正常。它用双引号将 HTTP header 中的边
我正在尝试使用 HttpContent: HttpContent myContent = HttpContent.Create(SOME_JSON); ...但是我没有运气找到它定义的 DLL。 首先
我正在研究应该完成简单事情的自定义过滤器。我所有的 API 都包装到“响应”对象中。我想使用过滤器填写所有属性。这是我的过滤器代码: public class MeteringFilter : IAc
我已经创建了一个 API,它应该能够通过 POST 和字符串形式的请求主体连接到外部 API。 我可以毫不费力地直接从 Postman 连接到 API。但是它不能通过我自己的 API 工作。 有什么想
我有一个通过 HttpSelfHostServer (ASP.Net WebApi Beta) 运行的小型 REST 服务,但在反序列化一些发布到服务器的数据时遇到了一些问题。方法签名如下: publ
我正在将 HttpContent 转换为以下 dto: public class ContentDto { public string ContentType {get; set;}
我正在使用 HttpClient.PostAsync() 并且响应是 HttpResponseMessage。它的 Content 属性是 HttpContent 类型,它有一个 CopyToAsyn
使用 Web API 2.2,假设我想从 HttpContent 中读取两次,每次都是不同的类型。 await httpContent.LoadIntoBufferAsync(); //necessa
我在网络上看到大量使用新 HttpClient 的示例对象(作为新 Web API 的一部分)应该有 HttpContent.ReadAsAsync方法。然而,MSDN没有提到这个方法,Intelli
这个问题在这里已经有了答案: POSTing JsonObject With HttpClient From Web API (10 个答案) Send HTTP POST message in A
尝试将文件添加到 http rest 调用时出现此错误: responseJson = {Message: "An error has occurred.", ExceptionMessage: "I
我正在设置一个 API 来与数据库交互,当该 API 收到一个帖子以创建一个已经存在于它的相应表中的条目时,我想返回一个带有解释性消息的代码 209 冲突。所以我尝试了这个: Controller p
我尝试创建 Windows 应用商店应用。我需要发送邮寄请求,但我遇到了问题。我的方法: private async Task POST(byte[] pic, string uploa
我正在使用 Microsoft.AspNet.WebApi.Client在我的 ASP.MVC 5 项目中使用休息服务。我正在关注 this使用 HttpClient 的教程。代码未编译,因为 Rea
我目前正在开发 C# Web API。对于特定调用,我需要使用对 API 的 ajax 调用发送 2 个图像,以便 API 可以将它们保存为数据库中的 varbinary(max)。 如何从 Http
我们正在构建一个高度并发的 Web 应用程序,最近我们开始广泛使用异步编程(使用 TPL 和 async/await)。 我们有一个分布式环境,其中应用程序通过 REST API(构建在 ASP.NE
我正在集成一个从几乎端点返回此模型的 API { meta: { ... }, data: { ... } } 但对于某些调用,数据是同类对象的数组 { meta: { ... },
在我的 Owin 自托管 Web Api 项目中,我正在尝试构建一个 custom MediaTypeFormatter继承自 BufferedMediaTypeFormatter 。但问题是Http
我正在尝试将以下读取 HttpContent 的完整字符串响应的代码转换为字符串,以仅读取特定的最大字符数。现有代码: private static async Task GetContentStri
我是一名优秀的程序员,十分优秀!