我想编写一个 Web Api 控制器操作,根据结果发送电子邮件。我想使用带有数据模型的 MVC 视图或部分视图来呈现电子邮件正文。
有没有办法做到这一点?
我想要这样的东西:
public class NotificationApiController : ApiController
{
private IMkpContext db;
public string ViewNotifications()
{
var dataModel = GetDataModel();
if (dataModel != null)
{
SendEmail(dataModel.ToAddress, dataModel.FromAddress, dataModel.Subject, RenderBody("viewName", dataModel);
}
return string.Empty;
}
}
Run Code Online (Sandbox Code Playgroud)
其中 RenderBody 将查找 viewName,用 dataModel 中的数据填充它,并将 View 呈现为字符串。
我是 .NET /MVC/ Web API 的新手。我创建了一个 .Net Web API,它接受输入参数查询 OracleDatabase 并以 JSON 形式返回结果。几乎遵循简单的 C# 代码。我的控制器看起来像
public class DataController : ApiController
{
[HttpGet]
public HttpResponseMessage Getdetails(string ROOM, DateTime DOB_GT)
{
List<OracleParameter> prms = new List<OracleParameter>();
prms.Add(new OracleParameter("ROOM", OracleDbType.Varchar2, ROOM, ParameterDirection.Input));
prms.Add(new OracleParameter("DOB_GT", OracleDbType.Date, DOB_GT, ParameterDirection.Input));
string connStr = ConfigurationManager.ConnectionStrings["SDataBaseConnection"].ConnectionString;
using (OracleConnection dbconn = new OracleConnection(connStr))
{
DataSet userDataset = new DataSet();
var strQuery = "SELECT * from SAMPLE_RESULTS_VW where ROOM = :ROOM and DOB > :DOB_GT ";
var returnObject = new …Run Code Online (Sandbox Code Playgroud) [HttpPost("xxxxxxxxxx")]
[Authorize(Roles = "xxxxxxxxx")]
public IActionResult Post([FromBody]xxxxxxx xxxxxxxxxxxxxx)
{
if (s == null)
{
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码是属性Authorize(Roles ="Director")。我的申请角色是学生、总监、经理。这个特定的方法只能由主管访问,并且对于上述方法它给我返回 401 未经授权。
export function xxxxxxxxxxxx(token, formValues) {
return axios.post(`${ROOT_URL}/xxxxxxx/xxxxxxxx`, formValues);
}
}
Run Code Online (Sandbox Code Playgroud)
我不确定如何通过 axios 调用在标头中发送不记名令牌。
我的 API 使用不记名令牌进行身份验证,控制器使用 Authorize 属性。
每当我使用邮递员查询 API 时。由于某种原因,它会在每个请求中发送一个 ARRAffinity cookie 以及不记名令牌。
但是,当我在没有 cookie 的情况下使用 fiddler 调用相同的 API 端点时。它随机失败并返回 401。是的,一些请求会随机获得 200 成功,而另一些则会失败并返回 401。
但是,当我通过 fidler 传递 ARRAffinity cookie 时。它可以正常工作,不会出现任何故障。
有没有办法阻止 Web Api 或 azure 生成 ARRAffinity cookie。我只想使用不记名而不是cookie。
是否可以在 Web API 中检索执行控制器和操作名称?我怎样才能实现一种方法来为我做到这一点?
我试图从Linux中的环境变量中获取connectionString,但问题是它返回null。
当我输入printenv connectionStringtermial 时,它返回变量,但在我编写的应用程序中,System.Environment.GetEnvironmentVariable("connectionString")它返回 null。
有谁知道为什么会发生这种情况?
ps 我正在 Docker 中运行应用程序。
linux environment-variables asp.net-web-api docker .net-core
我正在使用 epplus 库下载带有密码的 Excel 文件。下载部分工作正常。
public ActionResult DownloadExcel()
{
string sFileName = string.Empty;
using (ExcelPackage package = projectBL.DownloadExcel(ID, id1, id3, id4, id5))
{
System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
{
FileName = package.File.Name,
};
Response.Headers.Add("Content-Disposition", cd.ToString());
return File(package.GetAsByteArray("password"), "application/vndopenxmlformats-officedocument.spreadsheetml.sheet");
}
}
Run Code Online (Sandbox Code Playgroud)
但每当我尝试上传此受密码保护的文件时,都会出现以下错误
该文件不是有效的包文件。如果文件已加密,请在构造函数中提供密码。
因此,我通过提供读取文件所需的密码解决了上述错误。下面是相同的代码。
public ActionResult UploadExcel()
{
if (Request.Form.Files != null && Request.Form.Files.Count > 0)
{
var fileObject = Request.Form.Files[0];
string fileName = ContentDispositionHeaderValue.Parse(fileObject.ContentDisposition).FileName.Trim('"');
var Stream = fileObject.OpenReadStream();
ExcelPackage package = new ExcelPackage(Stream,"password");
projectBL.SaveData(package);
return Json("Records Saved Succesfully.");
}
} …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 JMeter 测试 Web API。Web 服务器在 JMeter 和数据库之间进行交互。服务器应该从 HTTP POST 请求中的 JSON 获取参数并将它们解析为查询。
相关控制器中Web服务器的代码如下所示:
[HttpPost]
[Route("my_awesome_route_path")]
public async Task<List<QueryResult>> invoice([FromBody]InvoiceInfo invoiceInfo)
{
query = string.Format("INSERT INTO my_awesome_table (`my`,`awesome`,`columns`) " +
"VALUES ({0},{1},{2});", invoiceinfo.awesomeparam1, ... ,invoiceinfo.awesomeparamn);
noRowsInserted = await db.Database.ExecuteSqlCommandAsync(query);
Run Code Online (Sandbox Code Playgroud)
在我的 JMeter HTTP 请求表单中,我输入了上述控制器功能的正确路径。我将参数和文件上传选项卡留空,同时使用以下内容填充正文数据选项卡:
${__FileToString(/my/awesome/file/path${__eval({awesome_json_file_name_with_no_dottxt_in_end_altough_it_has_it})}.txt,,)}
Run Code Online (Sandbox Code Playgroud)
在没有主体数据的情况下运行服务器确实会到达我设置的断点。所以我知道路线没问题。将上述代码添加到正文数据会导致 415 错误 - 不支持的媒体类型。以下是 JMeter 输出文件提供的 httpsample:
<httpSample t="8023" it="0" lt="8023" ct="2" ts="1544434665189" s="false" lb="HTTP Request" rc="415" rm="Unsupported Media Type" tn="Thread Group 1-3" dt="text" by="382" sby="281" ng="1" na="1">
<responseHeader class="java.lang.String">HTTP/1.1 415 Unsupported Media Type
Cache-Control: …Run Code Online (Sandbox Code Playgroud) 当我使用 Web api 调用下载文件时,我可以轻松下载该文件。唯一的问题是,在我的错误日志中发送 HTTP 标头后,我收到“服务器无法设置状态”。抱歉,如果这可能是重复的问题,但这里的答案都没有帮助我。
<a href="/api/DownloadDocumentById?documentId=<%=doc.Id %>" download>
<i class="fa fa-download text-primary"></i>
</a>
Run Code Online (Sandbox Code Playgroud)
<HttpGet>
<ActionName("DownloadDocumentById")>
Public Function DownloadDocumentById(documentId As Integer)
Dim document = xxxxxxxx
Dim context = HttpContext.Current
context.Response.ContentType = document.Type
context.Response.OutputStream.Write(document.Content, 0, document.Size)
context.Response.AddHeader("Content-Disposition", Baselib.FormatContentDispositionHeader($"{document.Name}"))
context.Response.AddHeader("Last-Modified", DateTime.Now.ToLongDateString())
context.Response.Flush()
context.Response.End()
Return HttpStatusCode.OK // Have also tried to create a sub without returning a value
End Function
Run Code Online (Sandbox Code Playgroud)
如前所述,我可以轻松下载该文档,但 IIS 仍然记录“HTTP 标头已发送后服务器无法设置状态”错误。再次抱歉,这是一个重复的问题。希望可以有人帮帮我。
vb.net webforms download asp.net-web-api asp.net-apicontroller
我正在尝试将 json 字符串发布到 Web API,目前得到了以下代码:
async Task<Uri> Post(CapturedImage image)
{
string json = JsonConvert.SerializeObject(image);
var content = new StringContent(json.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
response.EnsureSuccessStatusCode();
Debug.Log("Request Message Information:- \n\n" + response.RequestMessage + "\n");
Debug.Log(json.ToString());
// return URI of the created resource.
return response.Headers.Location;
}
Run Code Online (Sandbox Code Playgroud)
代码尚未完成,所以我不确定这是否是我最终想要返回的类型(最终我将有一个新的 json 字符串,其中包含有关特定汽车的信息)。
当涉及到线路时,Unity 挂起HttpResponseMessage response = await client.PostAsync(url, content);,我必须强行关闭 Unity 应用程序。
怎样才能httpClient成功使用呢?unityWebRequest我暂时没有使用它,因为我不明白WWWForm发送的方式(就像我猜的对象)。我也不希望发送 byte[],而是发送 json 字符串,我可以假设它WWWForm就像 json 字符串,但是分开的。另外,当它是WWWForm. 就像它是一个 json 字符串一样,我只有像这样的参数 …