我有這個API,它調用存儲過程中插入一個值,它在存儲過程中幾個PRINT語句從SQL Server存儲過程返回自定義消息的Web API C#
public class ConfirmJobController : ApiController
{
[HttpPost]
public IHttpActionResult Post(JobConfirmation confirmation)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
string outputMessage;
con.Open();
SqlCommand cmd = new SqlCommand("usp_PhoneApp_ConfirmBooking", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@p_jobId", confirmation.JobID);
cmd.Parameters.AddWithValue("@p_jobStatus", confirmation.JobStatus);
cmd.Parameters.AddWithValue("@p_createdDate", confirmation.CreatedDate);
cmd.ExecuteNonQuery();
con.InfoMessage += delegate (object sender1, SqlInfoMessageEventArgs e1)
{
outputMessage = e1.Message;
};
return outputMessage;
}
}
}
我想從存儲過程獲取自定義消息到API的返回值。我怎樣才能做到這一點?
當前行回報outputMessage給出了一個錯誤「使用未賦值的變量,並不能隱式轉換字符串IHttpActionResult」
任何幫助是極大的讚賞。
這些是兩個非常無關的問題。第一個是[使用未分配的本地變量是什麼意思?](http://stackoverflow.com/q/5710485/11683)的副本,第二個是[Web API 2中的返回字符串]的副本, (http://stackoverflow.com/q/35344226/11683) – GSerg
您只分配回調中的消息,因此,它沒有被分配,編譯器正確地確定它只會在事件處理程序被命中後才被分配。此外,字符串不是IHttpActionResult,但是您可以返回(在收到正確消息後)'Ok(outputMessage)' – Icepickle
此外,混合控制器與數據訪問一樣沒有完成,如果您再次需要相同的功能,它會導致代碼重複和代碼維護'地獄' – Icepickle